package com.ouyunc.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ouyunc.cache.redis.RedisFactory;
import com.ouyunc.cache.redis.builder.RedisBuilder;
import com.ouyunc.common.constant.CommonConstant;
import com.ouyunc.im.constant.CacheConstant;
import com.ouyunc.im.constant.IMConstant;
import com.ouyunc.im.domain.ImGroup;
import com.ouyunc.im.domain.ImGroupUser;
import com.ouyunc.im.domain.ImUser;
import com.ouyunc.im.domain.bo.ImGroupUserBO;
import com.ouyunc.user.entity.dto.ImTempChatDTO;
import com.ouyunc.user.entity.dto.ImUserDetailDTO;
import com.ouyunc.user.entity.dto.SearchInfo;
import com.ouyunc.user.mapper.ImGroupMapper;
import com.ouyunc.user.mapper.ImGroupUserMapper;
import com.ouyunc.user.mapper.ImUserMapper;
import com.ouyunc.user.service.ImGroupService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fzx
 */
@Service
public class ImGroupServiceImpl extends ServiceImpl<ImGroupMapper, ImGroup> implements ImGroupService {

    @Resource
    private ImUserMapper imUserMapper;

    @Resource
    private ImGroupMapper imGroupMapper;

    @Resource
    private ImGroupUserMapper imGroupUserMapper;

    /**
     * 群组搜索
     * @param username
     * @return
     */
    @Override
    public List<SearchInfo> search(String username) {
        List<SearchInfo> result = new ArrayList<>();
        QueryWrapper<ImGroup> imGroupQueryWrapper = new QueryWrapper<>();
        imGroupQueryWrapper.eq("id", username)
                .or()
                .like("group_name", username);
        List<ImGroup> imGroups = imGroupMapper.selectList(imGroupQueryWrapper);
        if (CollectionUtils.isNotEmpty(imGroups)) {
            result = imGroups.stream().map(imGroup -> new SearchInfo(imGroup.getId().toString(), imGroup.getGroupName(), imGroup.getGroupAvatar())).collect(Collectors.toList());
        }
        return result;
    }

    /**
     * 根据群组id获取群组详情信息
     * @param groupId
     * @return
     */
    @Override
    public ImUserDetailDTO getGroup(String userId, String groupId) {
        ImGroup imGroup = (ImGroup) RedisFactory.redisTemplate().opsForValue().get(CacheConstant.OUYUNC + CacheConstant.IM_USER + CacheConstant.GROUP + groupId);
        if (imGroup == null) {
            imGroup = imGroupMapper.selectById(groupId);
        }
        if (imGroup == null) {
            return  null;
        }
        ImUserDetailDTO imUserDetailDTO = new ImUserDetailDTO(imGroup.getId().toString(), imGroup.getGroupName(), imGroup.getGroupName(), imGroup.getGroupAvatar(), imGroup.getGroupAnnouncement());
        ImGroupUserBO imGroupUserBO = (ImGroupUserBO) RedisFactory.redisTemplate().opsForHash().get(CacheConstant.OUYUNC + CacheConstant.IM_USER + CacheConstant.GROUP + groupId + CacheConstant.MEMBERS, userId);
        if (imGroupUserBO != null) {
            imUserDetailDTO.setExistGroup(1);
            imUserDetailDTO.setIsLeader(imGroupUserBO.getIsLeader());
        }else {
            QueryWrapper<ImGroupUser> imGroupUserQueryWrapper = new QueryWrapper<>();
            imGroupUserQueryWrapper.eq("user_id", userId).eq("group_id", groupId);
            ImGroupUser imGroupUser = imGroupUserMapper.selectOne(imGroupUserQueryWrapper);
            if (imGroupUser != null) {
                imUserDetailDTO.setExistGroup(1);
                imUserDetailDTO.setIsLeader(imGroupUser.getIsLeader());
            }
        }
        return imUserDetailDTO;
    }

    /**
     * 创建群，并将自己设置为群主（群主是可以设置的 ）
     * @param userId
     * @param imGroup
     * @return
     */
    @Transactional
    @Override
    public ImGroup createGroup(String userId, ImGroup imGroup) {
        imGroup.setGroupAvatar("https://vkceyugu.cdn.bspapp.com/VKCEYUGU-dc-site/460d46d0-4fcc-11eb-8ff1-d5dcf8779628.png");
        imGroup.setStatus(IMConstant.GROUP_STATUS_0);
        imGroup.setMushin(IMConstant.NOT_MUSHIN);
        imGroup.setGroupJoinPolicy(IMConstant.GROUP_JOIN_AGREE_REFUSE);
        imGroupMapper.insert(imGroup);
        // 新增群成员，并设置为群主
        String userNickName = "";
        ImUser imUser = imUserMapper.selectById(userId);
        if (imUser != null) {
            userNickName = imUser.getNickName();
        }
        String nowDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        ImGroupUser imGroupUser = new ImGroupUser(null, imGroup.getId(), imGroup.getGroupName(), Long.valueOf(userId), userNickName, IMConstant.GROUP_LEADER, IMConstant.NOT_GROUP_MANAGER, IMConstant.NOT_SHIELD, IMConstant.NOT_MUSHIN, nowDateTime);
        imGroupUserMapper.insert(imGroupUser);
        ImGroupUserBO imGroupUserBO = new ImGroupUserBO(imGroup.getId().toString(), imGroupUser.getUserId().toString(), imUser.getUsername(), imUser.getNickName(), imGroup.getGroupName(), imUser.getEmail(), imUser.getPhoneNum(), imUser.getIdCardNum(), imUser.getAvatar(), imUser.getMotto(), imUser.getAge(), imUser.getSex(), IMConstant.GROUP_LEADER, IMConstant.NOT_GROUP_MANAGER, IMConstant.NOT_SHIELD, IMConstant.NOT_MUSHIN, nowDateTime);
        // 放入缓存
        RedisFactory.redisTemplate().opsForHash().put(CacheConstant.OUYUNC + CacheConstant.IM_USER + CacheConstant.GROUP + imGroup.getId() + CacheConstant.MEMBERS, imGroupUser.getUserId().toString() ,imGroupUserBO);
        RedisFactory.redisTemplate().opsForValue().set(CacheConstant.OUYUNC + CacheConstant.IM_USER + CacheConstant.GROUP + imGroup.getId(), imGroup);

        // 放入临时聊天记录列表
        RedisFactory.redisTemplate().opsForHash().putIfAbsent(CacheConstant.OUYUNC + CacheConstant.IM_USER + CommonConstant.TEMP_CHAT_CONTACT + userId, imGroup.getId().toString(), new ImTempChatDTO(imGroup.getId().toString(), imGroup.getGroupName(), imGroup.getGroupName(), imGroup.getGroupAvatar(), null,IMConstant.GROUP_TYPE_2, null));
        return imGroup;
    }

    /**
     * 取消群组管理员
     * @param groupId
     * @param originManagerUserId
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public int cancelGroupManager(String groupId, String originManagerUserId, Integer isManager) {
        // 修改数据库中的
        QueryWrapper<ImGroupUser> imGroupUserQueryWrapper = new QueryWrapper<>();
        imGroupUserQueryWrapper.eq("user_id", originManagerUserId).eq("group_id", groupId);
        ImGroupUser imGroupUser = imGroupUserMapper.selectOne(imGroupUserQueryWrapper);
        if (imGroupUser != null) {
            imGroupUser.setIsManager(isManager);
            imGroupUserMapper.updateById(imGroupUser);
            ImUser imUser = imUserMapper.selectById(originManagerUserId);
            // 更新缓存
            ImGroupUserBO imGroupUserBO = new ImGroupUserBO(groupId, originManagerUserId, imUser.getUsername(), imGroupUser.getUserNickName(), imGroupUser.getGroupNickName(), imUser.getEmail(), imUser.getPhoneNum(), imUser.getIdCardNum(), imUser.getAvatar(), imUser.getMotto(), imUser.getAge(), imUser.getSex(), imGroupUser.getIsLeader() ,isManager, imGroupUser.getIsShield(), imGroupUser.getMushin(), imGroupUser.getCreateTime());
            RedisFactory.redisTemplate().opsForHash().put(CacheConstant.OUYUNC + CacheConstant.IM_USER + CacheConstant.GROUP + groupId + CacheConstant.MEMBERS, originManagerUserId, imGroupUserBO);
        }
        return 1;
    }
}
